package com.pxxy.lawconsult.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.pxxy.lawconsult.bean.User;
import com.pxxy.lawconsult.constant.DBConstant;
import com.pxxy.lawconsult.utils.DBUtils;


@WebServlet("/FindPasswordServlet")
public class FindPasswordServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	public static final String FIND_PASSWORD = "findPassword";// json找回密码标签:key
    public static final String FINDPASSWORD_SUCCESS = "success";// json找回密码标签:value
    public static final String FINDPASSWORD_FAILURE = "failure";// json找回密码标签:value
    public static final String FINDPASSWORD_NOTFIND = "notFind";// json找回密码标签:value
    public static final String FINDPASSWORD_FAILURE_SERVER_ERROR = "serverError";// json找回密码标签:value
    private Gson gson;
    private Map<String, String> map;
	
    public FindPasswordServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		//获取请求数据
		String tel = request.getParameter(User.TEL);
		String newPassword = request.getParameter(User.PASSWORD);
		
		gson = new Gson();
		map = new HashMap<>();

		PrintWriter out = response.getWriter();

		//判断是否为空
		if (tel == null || tel.equals("") || tel.equals("null")) {
			map.put(FIND_PASSWORD,FINDPASSWORD_FAILURE);
			out.write(gson.toJson(map));
			return;
		} else if (newPassword == null || newPassword.equals("") || tel.equals("null")) {
			map.put(FIND_PASSWORD, FINDPASSWORD_FAILURE);
			out.write(gson.toJson(map));
			return;
		}
		
		//修改密码
		try {
			//先查询用户是否存在
			ResultSet result = DBUtils.query(DBConstant.TB_USER_TABLE, DBConstant.USER_TABLE_TEL, tel);
			if(result.next()) {
				int row = DBUtils.update(DBConstant.TB_USER_TABLE, DBConstant.USER_TABLE_PASSWORD, newPassword, DBConstant.USER_TABLE_TEL, tel);
				//判断修改是否成功
				if(row == 1) {
					map.put(FIND_PASSWORD, FINDPASSWORD_SUCCESS);
				}else {
					map.put(FIND_PASSWORD, FINDPASSWORD_FAILURE);
				}
			}else {
				//用户不存在
				map.put(FIND_PASSWORD, FINDPASSWORD_NOTFIND);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			String findPasswordJson = gson.toJson(map);
			//写出数据
			out.println(findPasswordJson);
			//关闭连接
			out.close();
			DBUtils.close();
		}
		
		
	}

}
